package com.sfac.springBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName="paramFilter", urlPatterns={"/*"})
public class ParamFilter implements Filter {
    public final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("======== Init Param Filter ========");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("======== DO Param Filter ========");

        HttpServletRequest requ = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(requ) {
            @Override
            public String getParameter(String name) {
                String value = requ.getParameter(name);
                return StringUtils.isBlank(value) ? value : value.toLowerCase().replaceAll("fuck", "****");
            }

            @Override
            public String[] getParameterValues(String name) {
                List<String> values = new ArrayList<>();
                String[] temp = super.getParameterValues(name);
//				for (String item : temp) {
//					values.add(item.toLowerCase().replaceAll("fuck", "***"));
//				}
//				return values.toArray(new String[values.size()]);

                return Arrays.asList(temp).stream()
                        .map(item -> item.toLowerCase().replaceAll("fuck", "***"))
                        .toArray(String[] :: new);
            }
        };

        chain.doFilter(requestWrapper, resp);
    }

    @Override
    public void destroy() {
        LOGGER.debug("======== Destroy Param Filter ========");
    }
}
